# -*- coding: cp1252 -*-
import logging.config, os, sys
import xbmc, xbmcgui, xbmcplugin #@UnresolvedImport
configRoot=os.path.join(os.getcwd(), "resources", "logging.conf")
try:
  logging.config.fileConfig(configRoot)
except:
  logging.basicConfig()
  logging.getLogger('root').exception('Failed to initialize logging... falling back to defaults.')

# Add the lib dir to path  
sys.path.append(os.path.join(os.getcwd(), 'lib'))

from utils import pluginsupport
import tvshack

# The list of modes of this plugin
LIST_CATEGORIES,PLAY_ITEM,LIST_PLAYABLE_ITEMS,LIST_EPISODES,SEARCH,RSS = 1,2,3,4,6,7

log = logging.getLogger("root")

log.info("calling with args: %s"%str(sys.argv))

url = None
name = None
mode = None
action = None
params = pluginsupport.parseArguments(sys.argv[2])
if len(params) > 0:
  log.debug("params: %s"%str(params))
  url = params["url"]
  name = params["name"]
  if params.has_key("action"):
    action = params['action']
  try:
    mode = int(params["mode"])
  except:
    log.exception("Could not parse mode. Args: %s"%str(params))

# first get metadata, then reload page 
if action == 'loadInfo':
  autoreload = xbmcplugin.getSetting("autoreload-metadata-update") == "true"
  if tvshack.loadInfo(url, name) and autoreload:
    xbmc.executebuiltin("Container.Refresh")
  elif autoreload:
    xbmcgui.Dialog().ok("Load Info...", "Failed!", "Could not load metadata for item: '%s'"%name)
else:
  items = []
  if mode == None or url == None or len(url) < 1:
    items = tvshack.listCategories()
  elif mode == LIST_CATEGORIES:
    if url.find('/tv/') >= 0:
      xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')
      log.debug("Setting content to tvshows...")
    elif url.find('/music') >= 0:
      xbmcplugin.setContent(int(sys.argv[1]), 'artists')
      log.debug("Setting content to artists...")
    else:
      xbmcplugin.setContent(int(sys.argv[1]), 'movies')
      log.debug("Setting content to movies...")      
    items = tvshack.listCategory(url, name)
  elif mode == LIST_EPISODES:
    xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
    log.debug("Setting content for to episodes...")
    items = tvshack.listEpisodes(url, name)
  elif mode == SEARCH:
    items = tvshack.doInteractiveSearch()
  elif mode == RSS:
    items = tvshack.RSS(url)

  if mode == PLAY_ITEM:
    items = tvshack.resolveFiles(url, name, forceSourceSelection=(action == "selectSource"))
    if len(items) > 1:
      playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
      # we need to append the parts to the playlist
      log.debug("Playing items: %s"%str(items))
      position = playlist.getposition()
      otherParts = items[1:]
      try:
        for index in range(len(otherParts)):
          playable = otherParts[index]
          partNumber = index+2
          log.debug("Appending part %s: %s %s" % (str(partNumber), playable.getTargetUrl(), str(position+partNumber)))
          playlist.add(playable.getTargetUrl(), playable.getListItem(), position+partNumber)
          log.debug("Appended part %s: %s" % (str(partNumber), playable.getTargetUrl()))
      except:
        log.exception("Failed adding items to playlist")
    log.debug("setting resolved url: %s"%items[0].getTargetUrl())
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, items[0].getListItem())
  else:  
    try:
      for item,count in items:
        targetUrl = item.getTargetUrl()
        listItem = item.getListItem()
        contextItems = [("Reload listing", "Container.Refresh")]
        loadTargetName = 'Re-load info'
        if item.metadata is None or not item.metadata.isImdb():
          loadTargetName = 'Load info'
        if xbmcplugin.getSetting("metadata-query-skip") == "false":
          contextItems.append((loadTargetName, "XBMC.RunPlugin(%s)"%item.getTargetUrl('loadInfo')))
        if xbmcplugin.getSetting("autoplay-preferred-source") == "true" and not item.isFolder():
          contextItems.append(("Select source", "XBMC.PlayMedia(%s)"%item.getTargetUrl('selectSource')))
        listItem.addContextMenuItems(contextItems)
        xbmcplugin.addDirectoryItem(int(sys.argv[1]), targetUrl, listItem, item.isFolder(), count)
    except:
      log.exception("Failed to add item! %s"%item.name)
    xbmcplugin.endOfDirectory(int(sys.argv[1]), cacheToDisc=mode!=1)
      